﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 删除权限
    /// </summary>
    public class DeletePermissionHandler : IRequestHandler<DeletePermissionResultDto, ApiResult>
    {
        private readonly IBaseReposiotry<Permissions> _permissionRepository;
        private readonly IBaseReposiotry<RolePermissions> _rolePermissionRepository;
        private readonly ILogger<DeletePermissionHandler> _logger;
        private readonly IMapper _mapper;
        private readonly UserDbContext _dbContext;

        public DeletePermissionHandler(IBaseReposiotry<Permissions> permissionRepository,
            IBaseReposiotry<RolePermissions> rolePermissionRepository,
            ILogger<DeletePermissionHandler> logger,
            IMapper mapper,
            UserDbContext dbContext)
        {
            _permissionRepository = permissionRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _logger = logger;
            _mapper = mapper;
            _dbContext = dbContext;
        }

        public async Task<ApiResult> Handle(DeletePermissionResultDto request, CancellationToken cancellationToken)
        {
            var role = await _rolePermissionRepository.GetAsync(x => x.PermissionId == request.PermissionsId);
            if (role != null)
            {
                return ApiResult.Error("权限已被使用，不能删除");
            }

            var obj = await _permissionRepository.GetAsync(x => x.PermissionsId == request.PermissionsId);
            //实体状态会设为delete
            _dbContext.Set<Permissions>().Remove(obj);
            //经过拦截器修改实体状态为modified
            await _dbContext.SaveChangesAsync();
            return ApiResult.Ok();
        }
    }
}

public class DeletePermissionResultDto : IRequest<ApiResult>
{
    /// <summary>
    /// 权限Id
    /// </summary>
    public int PermissionsId { get; set; }
}
